package com.acme.web;

import java.io.IOException;
import java.util.Collection;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.acme.domain.Customer;
import com.acme.service.DateService;

@WebServlet("/customers/*")
public class CustomersController extends HttpServlet {
	@PersistenceUnit private EntityManagerFactory entityManagerFactory;
	@Inject private DateService dateService;


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Customer customerForSave = new Customer(req.getParameter("customer_name"));
        entityManager.getTransaction().begin();
        entityManager.persist(customerForSave);
        entityManager.getTransaction().commit();
        entityManager.close();
        
        doGet(req, resp); //don't try this at home: better use business logic re-use
	}


	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Collection<Customer> customers = entityManager
        		.createNamedQuery("Customer.findAll", Customer.class)
        		.getResultList();
        entityManager.close();
        
        request.setAttribute("customers", customers);
        request.setAttribute("currentDate", dateService.getCurrentDate());
        getServletContext().getRequestDispatcher("/WEB-INF/customers.jsp").forward(request, response);
	}
}
